package com.moon.game.command.guest.lair;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.moon.game.command.BaseCmd;
import com.moon.game.command.RequestSession;
import com.moon.game.constants.Constants;
import com.moon.game.constants.ErrorCode;
import com.moon.game.exception.GException;
import com.moon.game.manager.AnimalChildMG;
import com.moon.game.manager.AnimalMG;
import com.moon.game.manager.ItemMG;
import com.moon.game.resource.model.Animal;
import com.moon.game.resource.model.AnimalChild;
import com.moon.game.resource.model.Item;
import com.moon.game.service.ChatService;
import com.moon.game.service.ItemService;
import com.moon.game.service.LairService;
import com.moon.game.service.PlayerService;
import com.moon.game.vos.ErrorMsg;
import com.moon.game.vos.PlayerVo;
import com.moon.game.vos.PlayerVo.Pet;
import com.moon.game.vos.PlayerVo.Tower;
import com.moon.game.vos.RentLairBean;

/**
 * @description 求助他人的珍兽孵蛋
 * @author Ranger 作者 E-mail:haozi000005@163.com
 * @version 创建时间：2012-8-1 下午3:17:49
 */
public class SeekHelpToIncubationCmd extends BaseCmd {
	
	private static final Logger log = Logger.getLogger(SeekHelpToIncubationCmd.class);

	@Override
	protected void runOnce(RequestSession req) throws GException {
		switch (req.getStatus()) {
			case STATU_INIT:
				doInit(req);
				break;
			case STATU_CHECK:
				doCheckSelf(req);
				break;
			case STATU_RETURN:
				doResponse(req);
				break;
			default:
				break;
		}
	}

	@Override
	protected void doResponse(RequestSession req) throws GException {
		String[] ps = req.getClientRequest().getPs();
		if (ps == null) {
			doResponsePsError(req);
			return;
		}
		
		String otherSid = ps[0];
		String otherPid = ps[1];
		Integer otherTowerId = Integer.parseInt(ps[2]);
		req.setVO("other_sid", otherSid);
		req.setVO("other_pid", otherPid);
		req.setVO("other_tower_id", otherTowerId);
		if (otherSid == null || otherPid == null || otherTowerId == null) {
			doResponsePsError(req);
			return;
		}
		
		//查找是否有该玩家
		PlayerVo other = PlayerService.doGetPlayer(otherSid, otherPid);
		if (other == null) {
			doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_NO_PLAYER, "你要求助的好友不存在！"));
			return;
		}
		
		//查找人物是否有该孵化塔
		List<Tower> hadTowers = other.getTowerList();
		boolean hasTheTower = true;
		Tower theTower = null;
		if (hadTowers == null) {
			hasTheTower = false;
		}else {
			for (Tower tower : hadTowers) {
				if (tower.getTowerId() == otherTowerId) {
					theTower = tower;
					hasTheTower = true;
					break;
				}
				hasTheTower = false;
			}
		}
		if (!hasTheTower) {
			doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_NO_TOWER, "你要求助的好友没有指定的孵化塔！"));
			return;
		}
		
		//查找租赁处是否有该孵化塔
		LinkedList<RentLairBean> rentingLairs = LairService.getRentingLairs();
		boolean hasFound = false;
		int price = 0;
		RentLairBean theBean = null;
		for (RentLairBean bean : rentingLairs) {
			if (bean.getSid().equals(otherSid) && bean.getPid().equals(otherPid) && bean.getTower().getTowerId() == otherTowerId) {
				//租赁处找到该孵化塔
				price = bean.getIncubationPrice();
				hasFound = true;
				if (bean.getTower().getAnimalId() != theTower.getAnimalId()) {
					bean.setTower(theTower);
					LairService.UpdataTheRendBean(rentingLairs, bean);
				}
				theBean = bean;
				break;
			}
		}
		if (!hasFound) {
			doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_NO_TOWER, "租赁处没有找到指定的孵化塔！"));
			return;
		}
		req.setVO("price", price);
		Integer sure = Integer.parseInt(ps[3]);
		if (sure == null) {
			doResponsePsError(req);
			return;
		}
		
		Animal animal = AnimalMG.instance.getAnimal(theTower.getAnimalId());
		if (animal == null) {
			log.error("can't find the animal:" + theTower.getAnimalId());
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "珍兽资源库中找不到指定珍兽！"));
			return;
		}
		req.setVO("animal_name", animal.getName());
		String des = "";
		switch (animal.getHierarchy()) {
		case 0:
			des = "凡兽";
			break;
		case 1:
			des = "仙兽";
			break;
		case 2:
			des = "神兽";
			break;
		}
		req.setVO("des", des);
		
		if (sure.intValue() == 1) {
			//确认孵化
			
			PlayerVo me = req.getPlayer();
			
			AnimalChild child = AnimalChildMG.instance.getAnimalChild(animal.getChildId());
			if (child == null) {
				log.error("can't find the child:" + animal.getChildId());
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "珍兽孵化资源库中找不到指定孵化兽！"));
				return;
			}
			
			//检测孵化需要消耗的耐久
			int erode = LairService.calcMinusLairEndure(1, 0);
			
			if (theTower.getCurrEndure() <= Constants.SEE_LAIR_MIN_ENDURE) {
				LairService.cancelTheRentingTower(theTower);
				ChatService.sendPrivateActMessage(null, otherPid, null, "你的孵化塔持久太低了，为了杜绝其他玩家孵化导致倒塌，该孵化塔已被退回，请尽快修复！", "TA_RL", String.valueOf(otherTowerId));
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_SYS, "租赁处：该孵化塔的持久太了，我要把他退回给他的主人，请你另选一个为你服务！"));
				return;
			}
			
			//人物等级必须要高于要孵化的珍兽等级才能进行孵化
			if (me.getLevel() < child.getLevel()) {
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_LACK_LEVEL, "等级低于需要孵化的珍兽等级不能进行孵化，要孵化" + child.getName() + "需要等级" + child.getLevel() + "！"));
				return;
			}
			//检测宠物列表长度
			List<Pet> petList = me.getPetList();
			if (petList == null) {
				petList = new ArrayList<Pet>();
			}
			if (petList.size() >= me.getPetYardCapacity()) {
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_MAX_PET_YARD_CAPACITY, "你的宠物院容量已经达到饱和，不能再容纳更多的宠物了！"));
				return;
			}
			
			//指定价格孵化
			boolean minusStatu = PlayerService.checkMoney(req.getSid(), req.getPlayerId(), price);
			if (!minusStatu) {
				doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_NO_MONEY, "你的金币不足" + price + "，不能进行珍兽孵化！"));
				return;
			}
			
			Item item = ItemMG.instance.getItem(animal.getEggId());
			if (item == null) {
				log.error("can't find the egg:" + animal.getEggId());
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "道具资源库中找不到指定道具！"));
				return;
			}
			
			int ret = ItemService.delItem(me, animal.getEggId(), 1);
			
			StringBuffer info = new StringBuffer();
			if (ret == Constants.DEL_ITEM_SUCC) {
				log.debug("del " + item.getName() + "succ!");
				//扣除金币孵化一次
				minusStatu = PlayerService.minusGold(req.getSid(), req.getPlayerId(), price);
				if (!minusStatu) {
					doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_NO_GOLD, "你的金币不足" + price + "，不能进行珍兽孵化！"));
					return;
				}
				log.debug("minuse " + price + "gold succ!");
				//扣除蛋成功
				Pet pet = AnimalChildMG.instance.petFactory(animal.getChildId());
				petList.add(pet);
				me.setPetList(petList);
				log.debug("add pet:" + animal.getChildId() + " succ!");
				synchronized(other) {
					//减持久
					theTower.setCurrEndure(theTower.getCurrEndure() - erode);
					//成功孵化次数加1
					theTower.setIncubationTimes(theTower.getIncubationTimes() + 1);
					//收取1成手续费
					int addPrice = (int)(price * 0.9);
					boolean addStatu = PlayerService.doAddGold(other, addPrice);
					if (addStatu) {
						//加钱成功的情况下已经有入库
						log.debug("seek help succ|" + otherSid + "|" + otherPid + "|" + addPrice);
					}else {
						PlayerService.doUpdatePlayer(otherSid, otherPid, other);
						log.error("seek help fail|" + otherSid + "|" + otherPid + "|" + addPrice);
					}
					//发送消息给孵化塔主
					ChatService.sendPrivateMessage(req.getPlayer(), otherPid, other.getName(), "在你的帮助下我成功孵化了" + pet.getName() + "，这里是" + addPrice + "金币，请笑纳！", false);
					LairService.UpdataTheRendBean(rentingLairs, theBean);
					if (theTower.getCurrEndure() <= Constants.SEE_LAIR_MIN_ENDURE) {
						//持久低于满持久的20%清理出租赁处
						LairService.cancelTheRentingTower(theTower);
						ChatService.sendPrivateMessage(null, otherPid, other.getName(), "你的孵化塔持久低于满持久的20%了，为了杜绝其他玩家孵化导致倒塌，租赁处将该孵化塔退回，待你修复后再进行出租！", false);
					}
				}
				info.append("孵化" + AnimalChildMG.instance.getAnimalChild(animal.getChildId()).getName() + "成功，金币扣除" + price + "！");
				req.setVO(TAG_INFO, info.toString());
			}else if (ret == Constants.DEL_ITEM_FAIL) {
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "行囊检测" + item.getName() + "异常！"));
				return;
			}else if (ret == Constants.DEL_ITEM_NOT_ENOUGH) {
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "您的" + item.getName() + "数量不够！"));
				return;
			}else if (ret == Constants.DEL_ITEM_LACK) {
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_RESOURCE, "您当前没有" + item.getName() + "！"));
				return;
			}
		}else {
			//孵化前询问
			req.setVO(TAG_ACK, true);
		}
		response(req, req.getClientResponse());
	}
}
